<template>
    <div>
        <div class="container">
            <el-main>
                <el-form ref="orderFormRef" :rules="orderFormRules" :model="orderForm" :label-width="formLabelWidth">
                    <el-main >
                        <el-form-item label="ID" prop="id" v-if="false">
                            <el-input v-model="orderForm.id" />
                        </el-form-item>
                        <!-- 常规信息 -->
                        <el-form-item label="选择会员" prop="memberId">
                            <el-input v-model="orderForm.memberId" clearable class="handle-input mr10" v-if="false"/>
                            <el-select v-model="orderForm.memberId" class="handle-select mr10" placeholder="请选择会员">
                                <el-option v-for="item in memberOption" :key="item.value" :label="item.label" :value="item.value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="选择收货地址" prop="memberAddressId">
                            <el-input v-model="orderForm.address" placeholder="选择收货地址" class="handle-input mr10" readonly clearable @click="func_openMemberAddressDialog" />
                            <el-input v-model="orderForm.memberAddressId" v-if="false" />
                        </el-form-item>
                        <el-form-item label="使用优惠券抵扣" prop="memberCouponId">
                            <el-input v-model="orderForm.couponAmount" placeholder="选择会员优惠券" class="handle-input mr10" readonly clearable @click="func_openCouponsDialog" />
                            <el-input v-model="orderForm.memberCouponId" v-if="false" />
                        </el-form-item>
                        <el-form-item label="选择商品" prop="productId">
                            <el-input v-model="orderForm.product" placeholder="选择换购商品" class="handle-input mr10" readonly clearable @click="func_openGoodsDialog" />
                            <el-input v-model="orderForm.productId" v-if="false" />
                        </el-form-item>
                        <el-form-item label="商品单价" prop="price">
                            <el-input v-model="orderForm.price" class="handle-input mr10" readonly />
                        </el-form-item>
                        <el-form-item label="单位积分" prop="points">
                            <el-input v-model="orderForm.points" class="handle-input mr10" readonly />
                        </el-form-item>
                        <el-form-item label="订购数量" prop="takeNum">
                            <el-input v-model="orderForm.takeNum" clearable class="handle-input mr10" @blur="func_calOrderAmount" />
                        </el-form-item>
                        <el-form-item label="订单金额" prop="orderAmount">
                            <el-input v-model="orderForm.orderAmount" clearable class="handle-input mr10"  />
                        </el-form-item>
                        <el-form-item label="订单说明" prop="orderMemo">
                            <el-input type="textarea" rows="5" v-model="orderForm.orderMemo" clearable class="handle-input mr10" maxlength="100" show-word-limit/>
                        </el-form-item>
                        <el-form-item label="是否包邮" prop="postType">
                            <el-switch v-model="orderForm.postType" class="handle-switch mr40" placeholder="设为默认" :active-value="1" :inactive-value="0" active-text="包邮费" inactive-text="不包邮费" />
                        </el-form-item>
                        <el-form-item label="邮费" prop="postAmount">
                            <el-input v-model="orderForm.postAmount" clearable class="handle-input mr10" />
                        </el-form-item>
                    </el-main>
                </el-form>
            </el-main>
            <el-footer>
                <el-button type="primary" @click="func_onSubmit" plain>保存数据</el-button>
                <el-button type="success" @click="func_onReset" plain>重置表单</el-button>
            </el-footer>
        </div>
        <el-dialog title="选择收件地址" v-model="vAddressDialogVisible" width="55%" :close-on-click-modal="false">
            <div class="handle-box">
                <VMemberAddress v-bind:selectValue="VAddressData" @AddressData="func_loadVMemberAddressData" />
            </div>
        </el-dialog>
        <el-dialog title="选择订单商品" v-model="vGoodsDialogVisible" width="55%" :close-on-click-modal="false">
            <div class="handle-box">
                <VGoods v-bind:selectValue="VGoodsData" @ProductData="func_loadVGoodsData" />
            </div>
        </el-dialog>
        <el-dialog title="选择平台优惠券" v-model="vCouponsDialogVisible" width="55%" :close-on-click-modal="false">
            <div class="handle-box">
                <VMemberCoupons v-bind:selectValue="VCouponsData" @CouponData="func_loadVCouponsData" />
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { onMounted, ref, reactive, toRefs, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from "element-plus";
import { findOrderInfoById, addGoodsOrder, saveGoodsOrder } from "../../../../api/hairmanager/order";
import { findMemberList } from "../../../../api/hairmanager/member";

import VMemberAddress from "../../../../components/MemberAddressSelector.vue"
import VMemberCoupons from "../../../../components/MemberCouponSelector.vue"
import VGoods from "../../../../components/GoodsSelector.vue"

import { NO_DATA_SELECT_ERROR, SUCCESS_ADDDATA_DIALOG_MESSAGE, SUCCESS_DELDATA_DIALOG_MESSAGE, SUCCESS_EDITDATA_DIALOG_MESSAGE, formLabelWidth, } from "../../../../api/CommonErrorMessage.js";

export default {
    name: "orderForm",
    components: {VMemberAddress, VMemberCoupons, VGoods},
	props:{
		selectValue: Object
	},
	emits: ["orderData"],
    setup(props, cex){
		onMounted(() => {
		});
        const router = useRouter();
		const route = useRoute();
        const formLabelWidth = ref("170px");
        const loadFlg = ref(false);
        const memberOption = ref([]);
		/**
         * @name 定义业务表单
         */
        const getInitFormData = () => {
            return {
                couponAmount: 0,
                id: 0,
                memberId: '',
                memberAddressId: '',
                address: '',
                memberCouponId: '',
                couponAmount: 0,
                price: "",
                points: "",
                product: "",
                productId: "",
                takeNum: 0,
                orderAmount: 0,
                orderMemo: '',
                orderPaySn: '',
                postAmount: 0,
                postType: 0,
			}
        };
        let id = 0;
        /**
         * @name 表单初始化
         */
        const resetOrderForm = () => {
            Object.assign(orderForm, getInitFormData());
            orderForm['id'] = id;
        };
		const orderForm = reactive(getInitFormData());
		const orderFormRef = ref(null);
        const orderFormRules = {
            gradeName: [
                { required: true, message: "请输入等级名称", trigger: "blur" },
            ],
            upWay: [
                { required: true, message: "请选择等级晋升方式", trigger: "blur" },
            ],
        };
		// =========================================================================================
		// 主业务处理 ========================================================================================= START
        // 提交
                const func_onSubmit = () => {
            // 表单校验
            orderFormRef.value.validate((valid) => {
                if (valid) {
                    if(loadFlg.value){
                        saveGoodsOrder(orderForm).then((res) => {
							if(res.code != 200) {
								ElMessage.error(res.message);
							} else {
								resetOrderForm();
								ElMessage.success(SUCCESS_EDITDATA_DIALOG_MESSAGE);
								cex.emit('orderData', {state: 1, data: []});
							}
						});
                    } else {
                        addGoodsOrder(orderForm).then((res) => {
							if(res.code != 200) {
								ElMessage.error(res.message);
							} else {
								resetOrderForm();
								ElMessage.success(SUCCESS_ADDDATA_DIALOG_MESSAGE);
								cex.emit('orderData', {state: 1, data: []});
							}
						});
                    }
                } else {
                    return false;
                }
            });
        };
        // 重置
        const func_onReset = () => {
			resetOrderForm();
        };
		const func_closeDialog = () => {
            cex.emit('orderData', {state: 1, data: []});
        };
        // 页面初始化
        const func_onload = (v) => {
			if(loadFlg.value){
				findOrderInfoById(v).then((res) => {
					Object.keys(orderForm).forEach((item) => {
                        orderForm[item] = res.data[item];
                    });
				});
			} else {
                resetOrderForm();
                load_MemberOpt();
			}
        }
        const load_MemberOpt = () => {
            findMemberList().then((res) => {
                res.data.forEach((item) => {
                    let obj = {value : item['id'], label : item['nickname']}
                    memberOption.value.unshift(obj);
                });
            });
        };
        const func_calOrderAmount = () => {
            orderForm['orderAmount'] = (orderForm['price'] * orderForm['takeNum']) - orderForm['couponAmount'];
        };
		// 主业务处理 ========================================================================================= END
        // 扩展业务处理 ========================================================================================= START
        const VAddressData = reactive({});
        const vAddressDialogVisible = ref(false);
        const func_openMemberAddressDialog = () => {
            if(orderForm['memberId'] === null || orderForm['memberId'].length ===0 ){
                ElMessage.error('请选择会员');
                return;
            } else {
                VAddressData['load'] = true;
                VAddressData['id'] = orderForm['memberId'];
                vAddressDialogVisible.value = true;
            }
        };
        const func_loadVMemberAddressData = (v) => {
            if(v['state'] === 1) {
                orderForm['address'] = v['address'];
                orderForm['memberAddressId'] = v['id'];
                vAddressDialogVisible.value = false;
            } else {
                vAddressDialogVisible.value = true;
            }
        };
        // 扩展业务处理 ========================================================================================= END
        // 扩展业务处理 ========================================================================================= START
        const VGoodsData = reactive({});
        const vGoodsDialogVisible = ref(false);
        const func_openGoodsDialog = () => {
            VGoodsData['load'] = true;
            VGoodsData['id'] = orderForm['memberId'];
            vGoodsDialogVisible.value = true;
        };
        const func_loadVGoodsData = (v) => {
            if(v['state'] === 1) {
                orderForm['product'] = v['product'];
                orderForm['productId'] = v['id'];
                orderForm['points'] = v['points'];
                orderForm['price'] = v['price'];
                vGoodsDialogVisible.value = false;
            } else {
                vGoodsDialogVisible.value = true;
            }
        };
        // 扩展业务处理 ========================================================================================= END
        // 扩展业务处理 ========================================================================================= START
        const VCouponsData = reactive({});
        const vCouponsDialogVisible = ref(false);
        const func_openCouponsDialog = () => {
            if(orderForm['memberId'] === null || orderForm['memberId'].length ===0 ){
                ElMessage.error('请选择会员');
                return;
            } else {
                VCouponsData['load'] = true;
                VCouponsData['id'] = orderForm['memberId'];
                vCouponsDialogVisible.value = true;
            }
        };
        const func_loadVCouponsData = (v) => {
            if(v['state'] === 1) {
                orderForm['memberCouponId'] = v['id'];
                orderForm['couponAmount'] = v['coupon'];
                vCouponsDialogVisible.value = false;
            } else {
                vCouponsDialogVisible.value = true;
            }
        };
        // 扩展业务处理 ========================================================================================= END
        watch(() => props.selectValue, (val) => {
            id = val['id'];
            loadFlg.value = val['load'];
            func_onload(id);
        }, {deep: true,immediate: true});
        return {
			loadFlg, formLabelWidth, orderFormRules, orderFormRef, orderForm,
			resetOrderForm, getInitFormData, func_onload, func_onSubmit, func_onReset,
            memberOption, load_MemberOpt, func_calOrderAmount,
            // 扩展业务处理 ========================================================================================= START
            vAddressDialogVisible, VAddressData, func_openMemberAddressDialog, func_loadVMemberAddressData,
            // 扩展业务处理 ========================================================================================= START
            vGoodsDialogVisible, VGoodsData, func_openGoodsDialog, func_loadVGoodsData,
            // 扩展业务处理 ========================================================================================= START
            vCouponsDialogVisible, VCouponsData, func_openCouponsDialog, func_loadVCouponsData
        };
    },
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 300px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
</style>